#include <bits/stdc++.h>
using namespace std;


class Solution
{
public:
    int findMaxLength(vector<int>& nums)
    {
        int n = nums.size();
        int sum = 0;
        int MaxLength = 0;
        unordered_map<int, int> cnt{{0, -1}};
        for (int i = 0; i < n; i++)
        {
            sum += nums[i] == 1 ? 1 : -1;
            if(cnt.find(sum) != cnt.end())
            {
                MaxLength = max(MaxLength, i - cnt[sum]);
            }
            else
            {
                cnt[sum] = i;
            }
        }
        return MaxLength;
    }
};

